package com.patterns.iterator;

import java.util.ArrayList;
import java.util.List;

/**
 * 聚合对象，可进行迭代操作
 * @author huangke
 *
 */
public class Children {
	private List<Child> list = new ArrayList<Child>();

	public void add(Child child){
		this.list.add(child);
	}
	
	public void remove(Child child){
		this.list.remove(child);
	}
	
	//获得迭代器
	public Iterators iterators(){
		return new Iterators();
	}
	
	//迭代器
	private class Iterators implements Iterator{
		
		private int cursor;//游标，用于记录遍历位置

		public Object first() {
			cursor = 0;
			return list.get(cursor);
		}

		public Object next() {
			if (cursor < list.size()) {
				return list.get(cursor++);
			}
			return null;
		}

		public Object last() {
			cursor = list.size() - 1;
			return list.get(cursor);
		}

		public boolean hasNext() {
			return cursor < list.size();
		}

		public boolean isFirst() {
			return cursor == 0;
		}

		public boolean isLast() {
			return cursor == (list.size() - 1);
		}
		
	}
}


class Child{
	private String name;
	public Child(String name) {
		this.name = name;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
}